<template>
  <view class="task-detail-container">
    <!-- 顶部导航 -->
    <cu-custom bgColor="bg-gradual-blue" :isBack="true">
      <block slot="backText">返回</block>
      <block slot="content">任务详情</block>
      <block slot="right">
        <view class="flex align-center">
          <text class="cuIcon-refresh text-white margin-right-sm" @tap="refreshData"></text>
          <text class="cuIcon-more text-white" @tap="showActionSheet = true"></text>
        </view>
      </block>
    </cu-custom>

    <!-- 加载状态 -->
    <view v-if="loading" class="flex justify-center align-center" style="height: 400rpx;">
      <text class="cuIcon-loading2 cuIconfont-spin text-gray"></text>
      <text class="text-gray margin-left-sm">加载中...</text>
    </view>

    <!-- 任务信息 -->
    <view v-else-if="taskDetail" class="task-content">
      <!-- 基本信息卡片 -->
      <view class="cu-card case margin-top">
        <view class="cu-item shadow">
          <view class="cu-list menu-avatar">
            <view class="cu-item">
              <view class="cu-avatar round lg" :style="{backgroundColor: taskDetail.statusColor}">
                <text class="cuIcon-form text-white"></text>
              </view>
              <view class="content flex-sub">
                <view class="text-black text-bold">{{taskDetail.taskNo}}</view>
                <view class="text-gray text-sm flex align-center">
                  <text class="cuIcon-time margin-right-xs"></text>
                  <text>{{taskDetail.planStartDate}} - {{taskDetail.planEndDate}}</text>
                </view>
              </view>
              <view class="action">
                <view class="cu-tag" :class="taskDetail.statusClass">{{taskDetail.statusText}}</view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 进度信息 -->
      <view class="cu-card case margin-top">
        <view class="cu-item shadow">
          <view class="cu-bar bg-white justify-between">
            <view class="content">
              <text class="cuIcon-progress text-blue margin-right-xs"></text>
              <text class="text-bold">执行进度</text>
            </view>
            <view class="action">
              <text class="text-blue text-bold">{{taskDetail.progress}}%</text>
            </view>
          </view>
          <view class="padding">
            <view class="cu-progress round">
              <view class="bg-blue" :style="{width: taskDetail.progress + '%'}"></view>
            </view>
            <view class="flex justify-between margin-top-sm text-sm text-gray">
              <text>已完成: {{taskDetail.completedQuantity}}/{{taskDetail.planQuantity}}</text>
              <text>剩余: {{taskDetail.planQuantity - taskDetail.completedQuantity}}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 详细信息 -->
      <view class="cu-card case margin-top">
        <view class="cu-item shadow">
          <view class="cu-bar bg-white">
            <view class="content">
              <text class="cuIcon-info text-blue margin-right-xs"></text>
              <text class="text-bold">任务信息</text>
            </view>
          </view>
          <view class="cu-list menu">
            <view class="cu-item">
              <view class="content">
                <text class="text-gray">生产计划</text>
              </view>
              <view class="action">
                <text class="text-blue" @tap="viewPlan">{{taskDetail.planNo}}</text>
              </view>
            </view>
            <view class="cu-item">
              <view class="content">
                <text class="text-gray">工种</text>
              </view>
              <view class="action">
                <text>{{taskDetail.workTypeName}}</text>
              </view>
            </view>
            <view class="cu-item">
              <view class="content">
                <text class="text-gray">优先级</text>
              </view>
              <view class="action">
                <view class="cu-tag sm" :class="taskDetail.priorityClass">{{taskDetail.priorityText}}</view>
              </view>
            </view>
            <view class="cu-item">
              <view class="content">
                <text class="text-gray">负责人</text>
              </view>
              <view class="action">
                <text>{{taskDetail.assigneeName || '未分配'}}</text>
              </view>
            </view>
            <view class="cu-item" v-if="taskDetail.description">
              <view class="content">
                <text class="text-gray">任务描述</text>
              </view>
            </view>
          </view>
          <view v-if="taskDetail.description" class="padding-lr">
            <text class="text-sm">{{taskDetail.description}}</text>
          </view>
        </view>
      </view>

      <!-- 时间信息 -->
      <view class="cu-card case margin-top">
        <view class="cu-item shadow">
          <view class="cu-bar bg-white">
            <view class="content">
              <text class="cuIcon-time text-blue margin-right-xs"></text>
              <text class="text-bold">时间记录</text>
            </view>
          </view>
          <view class="cu-list menu">
            <view class="cu-item">
              <view class="content">
                <text class="text-gray">计划开始</text>
              </view>
              <view class="action">
                <text>{{taskDetail.planStartDate}}</text>
              </view>
            </view>
            <view class="cu-item">
              <view class="content">
                <text class="text-gray">计划结束</text>
              </view>
              <view class="action">
                <text>{{taskDetail.planEndDate}}</text>
              </view>
            </view>
            <view class="cu-item" v-if="taskDetail.actualStartDate">
              <view class="content">
                <text class="text-gray">实际开始</text>
              </view>
              <view class="action">
                <text>{{taskDetail.actualStartDate}}</text>
              </view>
            </view>
            <view class="cu-item" v-if="taskDetail.actualEndDate">
              <view class="content">
                <text class="text-gray">实际结束</text>
              </view>
              <view class="action">
                <text>{{taskDetail.actualEndDate}}</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 操作记录 -->
      <view class="cu-card case margin-top">
        <view class="cu-item shadow">
          <view class="cu-bar bg-white">
            <view class="content">
              <text class="cuIcon-list text-blue margin-right-xs"></text>
              <text class="text-bold">操作记录</text>
            </view>
          </view>
          <view class="cu-timeline">
            <view class="cu-time" v-for="(log, index) in taskDetail.logs" :key="index">
              <view class="cu-item">
                <view class="content bg-grey light">
                  <view class="text-sm text-bold">{{log.action}}</view>
                  <view class="text-xs text-gray margin-top-xs">
                    {{log.operatorName}} · {{log.createTime}}
                  </view>
                  <view v-if="log.remark" class="text-xs margin-top-xs">{{log.remark}}</view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部操作按钮 -->
    <view class="cu-tabbar-height"></view>
    <view class="cu-bar foot input" v-if="taskDetail">
      <view class="action">
        <button 
          v-if="canClaim" 
          class="cu-btn bg-blue margin-right-sm"
          @tap="claimTask"
        >
          领取任务
        </button>
        <button 
          v-if="canStart" 
          class="cu-btn bg-green margin-right-sm"
          @tap="startTask"
        >
          开始执行
        </button>
        <button 
          v-if="canPause" 
          class="cu-btn bg-orange margin-right-sm"
          @tap="pauseTask"
        >
          暂停任务
        </button>
        <button 
          v-if="canResume" 
          class="cu-btn bg-green margin-right-sm"
          @tap="resumeTask"
        >
          恢复任务
        </button>
        <button 
          v-if="canUpdateProgress" 
          class="cu-btn bg-cyan margin-right-sm"
          @tap="updateProgress"
        >
          更新进度
        </button>
        <button 
          v-if="canComplete" 
          class="cu-btn bg-red"
          @tap="completeTask"
        >
          完成任务
        </button>
      </view>
    </view>

    <!-- 操作菜单 -->
    <cu-modal :show="showActionSheet" @close="showActionSheet = false">
      <view class="cu-dialog">
        <view class="cu-bar bg-white justify-end">
          <view class="content">操作菜单</view>
          <view class="action" @tap="showActionSheet = false">
            <text class="cuIcon-close text-red"></text>
          </view>
        </view>
        <view class="padding-xl">
          <button class="cu-btn bg-blue lg block margin-bottom" @tap="editTask">编辑任务</button>
          <button class="cu-btn bg-green lg block margin-bottom" @tap="viewPlan">查看计划</button>
          <button class="cu-btn bg-orange lg block" @tap="viewHistory">操作历史</button>
        </view>
      </view>
    </cu-modal>

    <!-- 进度更新弹窗 -->
    <cu-modal :show="showProgressModal" @close="showProgressModal = false">
      <view class="cu-dialog">
        <view class="cu-bar bg-white justify-end">
          <view class="content">更新进度</view>
          <view class="action" @tap="showProgressModal = false">
            <text class="cuIcon-close text-red"></text>
          </view>
        </view>
        <view class="padding">
          <view class="cu-form-group">
            <view class="title">完成数量</view>
            <input 
              v-model="progressForm.completedQuantity" 
              type="number" 
              placeholder="请输入完成数量"
              :disabled="progressForm.loading"
            />
          </view>
          <view class="cu-form-group">
            <view class="title">进度说明</view>
            <textarea 
              v-model="progressForm.remark" 
              placeholder="请输入进度说明（可选）"
              :disabled="progressForm.loading"
            ></textarea>
          </view>
          <view class="padding-top">
            <button 
              class="cu-btn bg-blue lg block"
              :loading="progressForm.loading"
              @tap="submitProgress"
            >
              确认更新
            </button>
          </view>
        </view>
      </view>
    </cu-modal>

    <!-- 完成任务弹窗 -->
    <cu-modal :show="showCompleteModal" @close="showCompleteModal = false">
      <view class="cu-dialog">
        <view class="cu-bar bg-white justify-end">
          <view class="content">完成任务</view>
          <view class="action" @tap="showCompleteModal = false">
            <text class="cuIcon-close text-red"></text>
          </view>
        </view>
        <view class="padding">
          <view class="cu-form-group">
            <view class="title">实际完成数量</view>
            <input 
              v-model="completeForm.actualQuantity" 
              type="number" 
              placeholder="请输入实际完成数量"
              :disabled="completeForm.loading"
            />
          </view>
          <view class="cu-form-group">
            <view class="title">质量等级</view>
            <picker 
              :value="completeForm.qualityLevelIndex" 
              :range="qualityLevels" 
              range-key="label"
              @change="onQualityLevelChange"
              :disabled="completeForm.loading"
            >
              <view class="picker">
                {{qualityLevels[completeForm.qualityLevelIndex].label}}
              </view>
            </picker>
          </view>
          <view class="cu-form-group">
            <view class="title">完成备注</view>
            <textarea 
              v-model="completeForm.remark" 
              placeholder="请输入完成备注（可选）"
              :disabled="completeForm.loading"
            ></textarea>
          </view>
          <view class="padding-top">
            <button 
              class="cu-btn bg-red lg block"
              :loading="completeForm.loading"
              @tap="submitComplete"
            >
              确认完成
            </button>
          </view>
        </view>
      </view>
    </cu-modal>
  </view>
</template>

<script>
import productionPlanV2 from '@/api/mes/productionPlanV2.js'
import authService from '@/common/auth/authService.js'

export default {
  data() {
    return {
      taskId: '',
      taskDetail: null,
      loading: true,
      showActionSheet: false,
      showProgressModal: false,
      showCompleteModal: false,
      
      // 进度更新表单
      progressForm: {
        completedQuantity: '',
        remark: '',
        loading: false
      },
      
      // 完成任务表单
      completeForm: {
        actualQuantity: '',
        qualityLevelIndex: 0,
        remark: '',
        loading: false
      },
      
      // 质量等级选项
      qualityLevels: [
        { value: 'A', label: 'A级 - 优秀' },
        { value: 'B', label: 'B级 - 良好' },
        { value: 'C', label: 'C级 - 合格' },
        { value: 'D', label: 'D级 - 不合格' }
      ]
    }
  },
  
  computed: {
    // 是否可以领取任务
    canClaim() {
      return this.taskDetail && 
             this.taskDetail.status === 'pending' && 
             !this.taskDetail.assigneeId &&
             authService.hasPermission('production:task:claim')
    },
    
    // 是否可以开始任务
    canStart() {
      return this.taskDetail && 
             this.taskDetail.status === 'assigned' && 
             this.isMyTask() &&
             authService.hasPermission('production:task:start')
    },
    
    // 是否可以暂停任务
    canPause() {
      return this.taskDetail && 
             this.taskDetail.status === 'in_progress' && 
             this.isMyTask() &&
             authService.hasPermission('production:task:pause')
    },
    
    // 是否可以恢复任务
    canResume() {
      return this.taskDetail && 
             this.taskDetail.status === 'paused' && 
             this.isMyTask() &&
             authService.hasPermission('production:task:resume')
    },
    
    // 是否可以更新进度
    canUpdateProgress() {
      return this.taskDetail && 
             this.taskDetail.status === 'in_progress' && 
             this.isMyTask() &&
             authService.hasPermission('production:progress:update')
    },
    
    // 是否可以完成任务
    canComplete() {
      return this.taskDetail && 
             (this.taskDetail.status === 'in_progress' || this.taskDetail.status === 'paused') && 
             this.isMyTask() &&
             authService.hasPermission('production:task:complete')
    }
  },
  
  onLoad(options) {
    this.taskId = options.id
    this.loadTaskDetail()
  },
  
  methods: {
    // 加载任务详情
    async loadTaskDetail() {
      this.loading = true
      try {
        const response = await productionPlanV2.getTaskDetail(this.taskId)
        this.taskDetail = this.processTaskData(response.data)
      } catch (error) {
        console.error('加载任务详情失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 处理任务数据
    processTaskData(task) {
      return {
        ...task,
        statusClass: this.calculateStatusClass(task),
        statusText: this.calculateStatusText(task),
        statusColor: this.calculateStatusColor(task),
        priorityClass: this.calculatePriorityClass(task),
        priorityText: this.calculatePriorityText(task),
        logs: task.logs || []
      }
    },
    
    // 计算状态样式类
    calculateStatusClass(task) {
      const statusMap = {
        'pending': 'bg-orange',
        'assigned': 'bg-blue',
        'in_progress': 'bg-cyan',
        'paused': 'bg-yellow',
        'completed': 'bg-green',
        'cancelled': 'bg-red'
      }
      return statusMap[task.status] || 'bg-gray'
    },
    
    // 计算状态文本
    calculateStatusText(task) {
      const statusMap = {
        'pending': '待领取',
        'assigned': '已分配',
        'in_progress': '进行中',
        'paused': '已暂停',
        'completed': '已完成',
        'cancelled': '已取消'
      }
      return statusMap[task.status] || '未知'
    },
    
    // 计算状态颜色
    calculateStatusColor(task) {
      const colorMap = {
        'pending': '#ff9500',
        'assigned': '#007aff',
        'in_progress': '#5ac8fa',
        'paused': '#ffcc00',
        'completed': '#34c759',
        'cancelled': '#ff3b30'
      }
      return colorMap[task.status] || '#8e8e93'
    },
    
    // 计算优先级样式类
    calculatePriorityClass(task) {
      const priorityMap = {
        'high': 'bg-red',
        'medium': 'bg-orange',
        'low': 'bg-blue'
      }
      return priorityMap[task.priority] || 'bg-gray'
    },
    
    // 计算优先级文本
    calculatePriorityText(task) {
      const priorityMap = {
        'high': '高',
        'medium': '中',
        'low': '低'
      }
      return priorityMap[task.priority] || '未设置'
    },
    
    // 判断是否为我的任务
    isMyTask() {
      const currentUser = authService.getCurrentUser()
      return this.taskDetail && this.taskDetail.assigneeId === currentUser.id
    },
    
    // 刷新数据
    async refreshData() {
      await this.loadTaskDetail()
      uni.showToast({
        title: '刷新成功',
        icon: 'success'
      })
    },
    
    // 领取任务
    async claimTask() {
      try {
        await productionPlanV2.claimTask(this.taskId)
        uni.showToast({
          title: '领取成功',
          icon: 'success'
        })
        await this.loadTaskDetail()
      } catch (error) {
        console.error('领取任务失败:', error)
        uni.showToast({
          title: '领取失败',
          icon: 'none'
        })
      }
    },
    
    // 开始任务
    async startTask() {
      try {
        await productionPlanV2.startTask(this.taskId)
        uni.showToast({
          title: '任务已开始',
          icon: 'success'
        })
        await this.loadTaskDetail()
      } catch (error) {
        console.error('开始任务失败:', error)
        uni.showToast({
          title: '开始失败',
          icon: 'none'
        })
      }
    },
    
    // 暂停任务
    async pauseTask() {
      try {
        await productionPlanV2.pauseTask(this.taskId)
        uni.showToast({
          title: '任务已暂停',
          icon: 'success'
        })
        await this.loadTaskDetail()
      } catch (error) {
        console.error('暂停任务失败:', error)
        uni.showToast({
          title: '暂停失败',
          icon: 'none'
        })
      }
    },
    
    // 恢复任务
    async resumeTask() {
      try {
        await productionPlanV2.resumeTask(this.taskId)
        uni.showToast({
          title: '任务已恢复',
          icon: 'success'
        })
        await this.loadTaskDetail()
      } catch (error) {
        console.error('恢复任务失败:', error)
        uni.showToast({
          title: '恢复失败',
          icon: 'none'
        })
      }
    },
    
    // 显示进度更新弹窗
    updateProgress() {
      this.progressForm.completedQuantity = this.taskDetail.completedQuantity.toString()
      this.progressForm.remark = ''
      this.showProgressModal = true
    },
    
    // 提交进度更新
    async submitProgress() {
      if (!this.progressForm.completedQuantity) {
        uni.showToast({
          title: '请输入完成数量',
          icon: 'none'
        })
        return
      }
      
      this.progressForm.loading = true
      try {
        await productionPlanV2.updateTaskProgress(this.taskId, {
          completedQuantity: parseInt(this.progressForm.completedQuantity),
          remark: this.progressForm.remark
        })
        
        uni.showToast({
          title: '进度更新成功',
          icon: 'success'
        })
        
        this.showProgressModal = false
        await this.loadTaskDetail()
      } catch (error) {
        console.error('更新进度失败:', error)
        uni.showToast({
          title: '更新失败',
          icon: 'none'
        })
      } finally {
        this.progressForm.loading = false
      }
    },
    
    // 显示完成任务弹窗
    completeTask() {
      this.completeForm.actualQuantity = this.taskDetail.planQuantity.toString()
      this.completeForm.qualityLevelIndex = 0
      this.completeForm.remark = ''
      this.showCompleteModal = true
    },
    
    // 质量等级选择变化
    onQualityLevelChange(e) {
      this.completeForm.qualityLevelIndex = e.detail.value
    },
    
    // 提交完成任务
    async submitComplete() {
      if (!this.completeForm.actualQuantity) {
        uni.showToast({
          title: '请输入实际完成数量',
          icon: 'none'
        })
        return
      }
      
      this.completeForm.loading = true
      try {
        await productionPlanV2.completeTask(this.taskId, {
          actualQuantity: parseInt(this.completeForm.actualQuantity),
          qualityLevel: this.qualityLevels[this.completeForm.qualityLevelIndex].value,
          remark: this.completeForm.remark
        })
        
        uni.showToast({
          title: '任务完成成功',
          icon: 'success'
        })
        
        this.showCompleteModal = false
        await this.loadTaskDetail()
      } catch (error) {
        console.error('完成任务失败:', error)
        uni.showToast({
          title: '完成失败',
          icon: 'none'
        })
      } finally {
        this.completeForm.loading = false
      }
    },
    
    // 编辑任务
    editTask() {
      this.showActionSheet = false
      uni.navigateTo({
        url: `/pages/production/task/edit?id=${this.taskId}`
      })
    },
    
    // 查看生产计划
    viewPlan() {
      this.showActionSheet = false
      uni.navigateTo({
        url: `/pages/production/plan/detail?id=${this.taskDetail.planId}`
      })
    },
    
    // 查看操作历史
    viewHistory() {
      this.showActionSheet = false
      uni.navigateTo({
        url: `/pages/production/task/history?id=${this.taskId}`
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.task-detail-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

.task-content {
  padding: 20rpx;
}

.cu-progress {
  height: 20rpx;
  
  .bg-blue {
    transition: width 0.3s ease;
  }
}

.cu-timeline {
  .cu-item {
    .content {
      border-radius: 10rpx;
      padding: 20rpx;
      
      .text-bold {
        color: #333;
      }
    }
  }
}

.cu-modal {
  .cu-dialog {
    border-radius: 20rpx;
    overflow: hidden;
  }
}

.cu-form-group {
  .title {
    min-width: 150rpx;
  }
  
  input, textarea {
    flex: 1;
  }
  
  .picker {
    flex: 1;
    text-align: right;
    color: #333;
  }
}

.cu-bar.foot {
  background: #fff;
  border-top: 1rpx solid #eee;
  
  .action {
    width: 100%;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    
    .cu-btn {
      min-width: 120rpx;
      height: 60rpx;
      line-height: 60rpx;
      font-size: 28rpx;
    }
  }
}
</style>
